#include "interface_pkg/srv/add_two_int.hpp"
#include "rclcpp/rclcpp.hpp"
#include <thread>

using namespace std::placeholders;

class ServiceClientNode : public rclcpp::Node {
public:
  ServiceClientNode(std::string node_name) : rclcpp::Node(node_name) {
    RCLCPP_INFO(this->get_logger(), "Service Client Node: %s",
                node_name.c_str());
    client_ = this->create_client<interface_pkg::srv::AddTwoInt>("add_two_int");
  }
  void start(int a, int b) {
    std::thread(std::bind(&ServiceClientNode::send_request, this, a, b))
        .detach();
  }
  void send_request(int a, int b) {
    if (!client_->wait_for_service(std::chrono::seconds(1))) {
      RCLCPP_ERROR(this->get_logger(), "Service not available");
      return;
    }
    auto request = std::make_shared<interface_pkg::srv::AddTwoInt::Request>();
    request->a = a;
    request->b = b;
    using ServiceResponseFuture =
        rclcpp::Client<interface_pkg::srv::AddTwoInt>::SharedFuture;
    auto response_callback = [this](ServiceResponseFuture) {};
    RCLCPP_INFO(this->get_logger(), "Sending request to service");
    auto future = client_->async_send_request(request, response_callback);
    if (future.get()->sum == -1) {
      RCLCPP_ERROR(this->get_logger(), "Service call failed");
      return;
    }
    RCLCPP_INFO(this->get_logger(), "Result of %d + %d = %d", a, b,
                future.get()->sum);
  }

private:
  rclcpp::Client<interface_pkg::srv::AddTwoInt>::SharedPtr client_;
};

int main(int argc, char **argv) {
  rclcpp::init(argc, argv);
  auto node = std::make_shared<ServiceClientNode>("service_client_node");
  node->start(1, 2);
  rclcpp::spin(node);
  rclcpp::shutdown();
  return 0;
}